//
//  PlayManager.m
//  BMS
//
//  Created by 颜魏 on 2021/4/16.
//

#import "PlayManager.h"
#import <AudioToolbox/AudioToolbox.h>
#import "GlobalDefine.h"

@interface PlayManager()

@property (strong, nonatomic) NSTimer *playMusicTimer;

@end

@implementation PlayManager

static SystemSoundID soundID = 0;

static PlayManager *shareManager;
+ (instancetype)sharedManager {
    if (!shareManager) {
        shareManager = [[super allocWithZone:NULL] init];
    }
    return shareManager;
}

- (void)playAudio {
    if (self.playMusicTimer) return;
    NSString *musicStr = [[NSBundle mainBundle] pathForResource:@"soundWarinng" ofType:@"wav"] ;
    NSURL *url = [NSURL fileURLWithPath:musicStr];
    // 音效的ID
    NSString *soundStatus = [[NSUserDefaults standardUserDefaults] objectForKey:PlaySoundState];
    if ([soundStatus isEqualToString:@"1"]) {
        AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
        AudioServicesPlaySystemSound(soundID);   // 播放音效
        AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
    }
    self.playMusicTimer = [NSTimer scheduledTimerWithTimeInterval:3 repeats:YES block:^(NSTimer * _Nonnull timer) {
        if (!self.isMute) {
            NSString *soundStatus = [[NSUserDefaults standardUserDefaults] objectForKey:PlaySoundState];
            if ([soundStatus isEqualToString:@"1"]) {
                AudioServicesCreateSystemSoundID((__bridge CFURLRef _Nonnull)(url), &soundID);
                AudioServicesPlaySystemSound(soundID);   // 播放音效
                AudioServicesPlaySystemSound(kSystemSoundID_Vibrate);
            }
        }
    }];
}

- (void)stopAudio {
    if (self.playMusicTimer) {
        [self.playMusicTimer invalidate];
        self.playMusicTimer = nil;
    }
}


@end
